<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入检索信息" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" clearable/>
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <el-select v-model="listQuery.type" placeholder="区域" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        Search
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="$router.push('/remove/index')">
        新增
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">-->
      <!--        Export-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        reviewer-->
      <!--      </el-checkbox>-->
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!--      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.id+1 }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="项目编号" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.value }}</span>
          <el-tag>{{ row.area | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="维修人员" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.person }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修联系电话" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合作银行" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bank | bankFilter }}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span style="color:red;">{{ row.reviewer }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="Imp" width="80px">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="Readings" align="center" width="95">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span v-if="row.pageviews" class="link-type" @click="handleFetchPv(row.pageviews)">{{ row.pageviews }}</span>-->
      <!--          <span v-else>0</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | stateFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdateimage(row)">
            上传图片
          </el-button>
          <!--          <el-button v-if="row.status!='published'" size="mini" type="success" @click="handleModifyStatus(row,'published')">-->
          <!--            Publish-->
          <!--          </el-button>-->
          <!--          <el-button v-if="row.status!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">-->
          <!--            Draft-->
          <!--          </el-button>-->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="项目名称" prop="value">
          <el-input :value="temp.value" />
        </el-form-item>
        <el-form-item label="项目编号" prop="num">
          <el-input :value="temp.num" />
        </el-form-item>
        <!--        <el-form-item label="更新时间" prop="timestamp">-->
        <!--          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date" />-->
        <!--        </el-form-item>-->
        <el-form-item label="合作银行" prop="bank">
          <el-input :value="temp.bank | bankFilter" />
        </el-form-item>
        <el-form-item label="维修人" prop="person">
          <el-input v-model="form.person" style="width: 46%" />
        </el-form-item>
        <el-form-item label="维修联系电话" prop="phone">
          <el-input v-model="form.phone" style="width: 46%" />
        </el-form-item>
        <el-form-item label="服务时间">
          <el-col :span="11">
            <el-date-picker
              v-model="DataSelect"
              type="daterange"
              unlink-panels
              format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="timestamp"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          返回
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData('dataForm')">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible_img">
      <el-form ref="imageForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 600px; margin-left:150px;">
        <el-form-item label="项目名称" prop="value">
          <el-input :value="temp.value" />
        </el-form-item>
        <el-form-item label="项目信息" prop="image">
          <el-upload
            ref="upload"
            class="upload-demo"
            multiple
            action="http://8.141.50.32/admin/subject/uploadfile"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="设备信息">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;" />
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in temp.device" :key="city" :label="city">{{ city }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible_img = false">
          返回
        </el-button>
        <el-button type="primary" @click="sbmitimgData_remove('imageForm')">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

import { getDeviceList_remove } from '@/api/device'
import { upimage_remove } from '@/api/subject'

import { scrollTo } from '@/utils/scroll-to'
import elementIcons from '@/views/icons/element-icons'

// 区域信息
const calendarTypeOptions = [
  { key: '371601', display_name: '市直管' },
  { key: '371602', display_name: '滨城区' },
  { key: '371604', display_name: '开发区' },
  { key: '371605', display_name: '高新区' },
  { key: '371606', display_name: '北海新区' },
  { key: '371621', display_name: '惠民县' },
  { key: '371622', display_name: '阳信县' },
  { key: '371623', display_name: '无棣县' },
  { key: '371624', display_name: '沾化区' },
  { key: '371625', display_name: '博兴县' },
  { key: '371626', display_name: '邹平市' },
  { key: '371627', display_name: '工业园区' }
]
// 状态信息
const calendarStateOptions = [
  { key: '0', display_name: '停工' },
  { key: '1', display_name: '开工' },
  { key: '2', display_name: '完工' },
  { key: '3', display_name: '筹建' },
  { key: '4', display_name: '立项' }
]
// 合作银行信息
const calendarBankOptions = [
  { key: '0', display_name: '农商银行' },
  { key: '1', display_name: '邮储银行' },
  { key: '2', display_name: '工商银行' },
  { key: '3', display_name: '恒丰银行' },
  { key: '4', display_name: '兴业银行' },
  { key: '5', display_name: '中国银行' },
  { key: '6', display_name: '东营银行' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
// 获取项目的状态信息
const calendarStateKeyValue = calendarStateOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})
// 获取合作银行的信息
const calendarBankKeyValue = calendarBankOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {

  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: 'success',
        2: 'info',
        0: 'danger',
        3: 'warning',
        4: 'error'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    },
    stateFilter(type) {
      return calendarStateKeyValue[type]
    },
    bankFilter(type) {
      return calendarBankKeyValue[type]
    }
  },
  data() {
    return {
      // 设备信息
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: true,

      // 文件列表
      fileList: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id',
        device: undefined
      },
      form: {
        person: '',
        phone: '',
        repair_time_end: '',
        repair_time_start: ''
      },
      // repair_phone:'',
      // repair_person:'',
      // repairtime_end:'',
      // repairtime_start:'',
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      // sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      calendarStateOptions: [],
      showReviewer: false,
      temp: {
        id: undefined,
        num: '',
        bank: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: '',
        person: '',
        phone: ''

      },
      dialogFormVisible: false,
      dialogFormVisible_img: false,
      dialogStatus: '',
      textMap: {
        update: '修改项目状态',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      DataSelect: [], // 时间
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        bank: [{ required: true, message: 'title is required', trigger: 'blur' }],
        state: [{ required: true, message: '请选择项目状态', trigger: 'change' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 显示设备信息
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.temp['device'] : []
      this.isIndeterminate = true
    },
    handleCheckedCitiesChange(value) {
      console.log(this.checkedCities)
      const checkedCount = value.length
      this.checkAll = checkedCount === this.temp['device'].length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.temp['device'].length
    },

    // 文件上传
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.image = ''
      for (const i in fileList) {
        this.image += fileList[i]['response'] + ';'
      }
    },
    handlePreview(file) {
      console.log(file)
    },
    handleSuccess(response, file, fileList) {
      this.image = ''
      for (const i in fileList) {
        this.image += fileList[i]['response'] + ';'
      }
    },
    getList(val) {
      this.listLoading = true
      if (val != undefined) {
        this.page = val.page,
        this.limit = val.limit
      }
      this.type = this.listQuery.type
      this.title = this.listQuery.title
      getDeviceList_remove(
        {
          page: this.page,
          state: 1,
          limit: this.limit,
          subject_area: this.type,
          subject_name: this.title
        }).then((res) => {
        if (res.code == '20000') {
          console.log(res.data)

          this.list = res.data
          // console.log(this.list)
          this.total = res.msg
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)

          // this.$message('提交成功!')
        } else {
          console.log('没有数据')
          this.$message({
            message: '提交失败，请联系管理员!',
            type: 'error'
          })
        }
      })
    },
    // 上传文件信息到维修表单中
    sbmitimgData_remove(imageForm) {
      this.$refs['imageForm'].validate((valid) => {
        const tempData = Object.assign({}, this.temp)
        // 获取上传的文件列表
        if (valid) {
          upimage_remove(
            {
              subject_image: this.image,
              subject_num: tempData.num,
              subject_remark: tempData.remark
            }).then((res) => {
            if (res.code == '20000') {
              // console.log(this.list)
              setTimeout(() => {
                this.listLoading = false
              }, 1.5 * 1000)
              if (res.data == 0) {
                this.$notify({
                  title: '信息',
                  message: '数据相同，无需重复提交',
                  type: 'warning',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: '信息',
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                console.log('b')
                this.dialogFormVisible_img = false
                console.log('e')
              }
            } else {
              this.$message({
                message: '提交失败，请联系管理员!',
                type: 'error'
              })
            }
          }).catch(err => {
            console.log('err', err)
          })
        }
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: '',
        type: '',
        id_s: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdateimage(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible_img = true
      this.$nextTick(() => {
        this.$refs['imageForm'].clearValidate()
      })
    },
    updateData(dataForm) {
      this.$refs['dataForm'].validate((valid) => {
        const tempData = Object.assign({}, this.temp)
        console.log(tempData)
        if (valid) {
          if (this.form.person == '') {
            var person = undefined
            var phone = undefined
          } else {
            var person = this.form.person
            var phone = this.form.phone
          }
          if (this.DataSelect == '') {
            var repair_time_end = undefined
            var repair_time_start = undefined
          } else {
            var repair_time_start = this.DataSelect[0]
            var repair_time_end = this.DataSelect[1]
          }
          UpdateRepair(
            {
              subject_num: tempData.num,
              id: tempData.id_s,
              repair_person: person,
              repair_phone: phone,
              repairtime_end: repair_time_end,
              repairtime_start: repair_time_start
            }).then((res) => {
            if (res.code == '20000') {
              // console.log(this.list)
              setTimeout(() => {
                this.listLoading = false
              }, 1.5 * 1000)

              //  this.$message('修改成功!')
              if (res.data == 0) {
                this.$notify({
                  title: '信息',
                  message: '数据相同，无需重复提交',
                  type: 'warning'
                })
              } else {
                this.$notify({
                  title: '信息',
                  message: '提交成功',
                  type: 'success'
                })
                this.dialogFormVisible = false
              }
            } else {
              this.$message({
                message: '提交失败，请联系管理员!',
                type: 'error'
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      console.log(row.num, index)
      DelSubject(
        {
          subject_num: row.num
        }).then((res) => {
        if (res.code == '20000') {
          // console.log(this.list)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)

          //  this.$message('修改成功!')
          if (res.data == 0) {
            this.$notify({
              title: '信息',
              message: '已删除，无需重复操作',
              type: 'warning',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '信息',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }
        } else {
          this.$message({
            message: '删除失败，请联系管理员史岩松!',
            type: 'error'
          })
        }
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
